/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2019-2021 十三 all rights reserved.
 * 版权所有，侵权必究！
 */
package ltd.newbee.mall.api.admin;

import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.newbee.mall.api.admin.param.BatchIdParam;
import ltd.newbee.mall.api.admin.param.BatchIdSendParam;
import ltd.newbee.mall.api.admin.param.RefundParam;
import ltd.newbee.mall.api.admin.vo.OrderExportVO;
import ltd.newbee.mall.api.mall.param.InvoiceApplyParam;
import ltd.newbee.mall.api.mall.vo.NewBeeMallOrderDetailVO;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.config.annotation.TokenToAdminUser;
import ltd.newbee.mall.config.constant.Log;
import ltd.newbee.mall.config.constant.PreventDuplicateSubmit;
import ltd.newbee.mall.dao.NewBeeMallOrderMapper;
import ltd.newbee.mall.entity.AdminUserToken;
import ltd.newbee.mall.service.NewBeeMallOrderService;
import ltd.newbee.mall.service.OrderGoodsReportService;
import ltd.newbee.mall.util.PageQueryUtil;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import ltd.newbee.mall.vo.GoodsReportVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 13
 * @qq交流群 796794009
 * @email 2449207463@qq.com
 * @link https://github.com/newbee-ltd
 */
@RestController
@Api(value = "v1", tags = "8-5.后台管理系统订单模块接口")
@RequestMapping("/manage-api/v1")
public class NewBeeAdminOrderAPI {

    private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminOrderAPI.class);

    @Resource
    private NewBeeMallOrderService newBeeMallOrderService;

    @Resource
    private NewBeeMallOrderMapper newBeeMallOrderMapper;



    @Resource
    private OrderGoodsReportService orderGoodsReportService;

    /**
     * 商品汇总报表
     */
    @RequestMapping(value = "/goodsReport", method = RequestMethod.GET)
    public Result goodsReport(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
                              @RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
                              @RequestParam(required = false) String startTime,
                              @RequestParam(required = false) String endTime,
                              @RequestParam(required = false) String billStatus,
                              @RequestParam(required = false) String refundStatus,@TokenToAdminUser AdminUserToken adminUser) {

        logger.info("商品汇总报表查询参数: pageNumber={}, pageSize={}, startTime={}, endTime={}, billStatus={}, refundStatus={}",
                pageNumber, pageSize, startTime, endTime, billStatus, refundStatus);

        // 设置默认分页参数
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        Map params = new HashMap(8);
        params.put("page", pageNumber);
        params.put("limit", pageSize);
        if (StringUtils.hasText(startTime)) {
            params.put("startTime", startTime);
        }
        if (StringUtils.hasText(endTime)) {
            params.put("endTime", endTime);
        }
        if (StringUtils.hasText(billStatus)) {
            params.put("billStatus", billStatus);
        }
        if (StringUtils.hasText(refundStatus)) {
            params.put("refundStatus", refundStatus);
        }

        PageQueryUtil pageUtil = new PageQueryUtil(params);
        GoodsReportVO report = orderGoodsReportService.getGoodsReport(pageUtil);
        return ResultGenerator.genSuccessResult(report);
    }

    /**
     * 商品订单明细
     */
    @RequestMapping(value = "/goods-order-details", method = RequestMethod.GET)
    public Result goodsOrderDetails(@RequestParam Long goodsId,
                                    @RequestParam(required = false) Integer pageNumber,
                                    @RequestParam(required = false) Integer pageSize,
                                    @RequestParam(required = false) String startTime,
                                    @RequestParam(required = false) String endTime,
                                    @RequestParam(required = false) String billStatus,
                                    @RequestParam(required = false) String refundStatus,
                                    @RequestParam(required = false) String goodsName) {

        logger.info("商品订单明细查询: goodsId={}, pageNumber={}, pageSize={}", goodsId, pageNumber, pageSize);

        if (goodsId == null) {
            return ResultGenerator.genFailResult("商品ID不能为空");
        }

        // 设置默认分页参数
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        Map params = new HashMap(8);
        params.put("page", pageNumber);
        params.put("limit", pageSize);
        params.put("goodsId", goodsId);
        if (StringUtils.hasText(startTime)) {
            params.put("startTime", startTime);
        }
        if (StringUtils.hasText(endTime)) {
            params.put("endTime", endTime);
        }
        if (StringUtils.hasText(billStatus)) {
            params.put("billStatus", billStatus);
        }
        if (StringUtils.hasText(refundStatus)) {
            params.put("refundStatus", refundStatus);
        }

        // 新增商品名称参数
        if (StringUtils.hasText(goodsName)) {
            params.put("goodsName", goodsName);
        }

        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(orderGoodsReportService.getGoodsOrderDetails(pageUtil));
    }

    @GetMapping("/exportGoodsReport")
    public void exportGoodsReport(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String billStatus,
            @RequestParam(required = false) String refundStatus,
            HttpServletResponse response) {

        try {
            orderGoodsReportService.exportGoodsReport(response, startTime, endTime, billStatus, refundStatus);
        } catch (Exception e) {
            throw new RuntimeException("导出商品汇总报表失败", e);
        }
    }



    /**
     * 导出商品订单明细
     */
    @GetMapping("/exportGoodsOrderDetails")
    public void exportGoodsOrderDetails(@RequestParam Long goodsId,
                                        @RequestParam(required = false) String startTime,
                                        @RequestParam(required = false) String endTime,
                                        @RequestParam(required = false) String billStatus,
                                        @RequestParam(required = false) String refundStatus,
                                        @RequestParam(required = false) String goodsName,
                                        HttpServletResponse response) {

        try {
            logger.info("导出商品订单明细: goodsId={}, startTime={}, endTime={}, billStatus={}, refundStatus={}",
                    goodsId, startTime, endTime, billStatus, refundStatus);

            orderGoodsReportService.exportGoodsOrderDetails(response, goodsId, startTime, endTime, billStatus, refundStatus,goodsName);
        } catch (Exception e) {
            logger.error("导出商品订单明细失败", e);
            throw new RuntimeException("导出商品订单明细失败", e);
        }
    }




    /**
     * 列表
     */
    @RequestMapping(value = "/orders", method = RequestMethod.GET)
    @ApiOperation(value = "订单列表", notes = "可根据订单号和订单状态筛选")
    public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
                       @RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
                       @RequestParam(required = false) @ApiParam(value = "订单号") String orderNo,
                       @RequestParam(required = false) @ApiParam(value = "订单状态") Integer orderStatus,
                       @RequestParam(required = false) @ApiParam(value = "开票状态") Integer isBill,
                       @RequestParam(required = false) @ApiParam(value = "开始时间") String startTime,
                       @RequestParam(required = false) @ApiParam(value = "结束时间") String endTime,
                       @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
            return ResultGenerator.genFailResult("分页参数异常！");
        }
        Map params = new HashMap(8);
        params.put("page", pageNumber);
        params.put("limit", pageSize);
        if (StringUtils.hasText(orderNo)) {
            params.put("orderNo", orderNo);
        }
        if (orderStatus != null) {
            params.put("orderStatus", orderStatus);
        }
        if (isBill != null) {
            params.put("isBill", isBill);
        }
        // 新增时间筛选参数
        if (StringUtils.hasText(startTime)) {
            params.put("startTime", startTime);
        }
        if (StringUtils.hasText(endTime)) {
            params.put("endTime", endTime);
        }
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(newBeeMallOrderService.getNewBeeMallOrdersPage(pageUtil));
    }


    /**
     * 导出Excel
     */
    /**
     * 导出Excel
     */
    @RequestMapping(value = "/exportOrder", method = RequestMethod.GET)
    @ApiOperation(value = "导出订单Excel", notes = "导出订单数据到Excel")
    public void exportOrders(@RequestParam(required = false) @ApiParam(value = "订单号") String orderNo,
                             @RequestParam(required = false) @ApiParam(value = "订单状态") Integer orderStatus,
                             @RequestParam(required = false) @ApiParam(value = "开票状态") Integer isBill,
                             @RequestParam(required = false) @ApiParam(value = "开始时间") String startTime,
                             @RequestParam(required = false) @ApiParam(value = "结束时间") String endTime,
                             HttpServletResponse response) {

        // 查询订单数据
        List<OrderExportVO> orderList = newBeeMallOrderMapper.selectOrdersForExport(
                orderNo, orderStatus, isBill, startTime, endTime
        );

        // 处理状态字段翻译
        List<OrderExportVO> processedOrderList = orderList.stream().map(order -> {
            // 翻译订单状态
            order.setOrderStatusText(getOrderStatusText(order.getOrderStatus()));

            // 翻译支付方式
            order.setPayTypeText(getPayTypeText(order.getPayType()));

            // 翻译开票状态
            order.setIsBillText(getBillStatusText(order.getIsBill()));

            // 翻译退款状态（如果有退款状态字段）
            if (order.getRefundStatus() != null) {
                order.setRefundStatusText(getRefundStatusText(order.getRefundStatus()));
            }

            return order;
        }).collect(Collectors.toList());

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            fileName = URLEncoder.encode("订单列表", "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 写入Excel
        try {
            EasyExcel.write(response.getOutputStream(), OrderExportVO.class)
                    .sheet("订单列表")
                    .doWrite(processedOrderList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取订单状态文本
     */
    private String getOrderStatusText(Integer orderStatus) {
        if (orderStatus == null) return "未知";

        switch (orderStatus) {
            case 0: return "待支付";
            case 1: return "已支付";
            case 2: return "配货完成";
            case 3: return "出库成功";
            case 4: return "交易成功";
            case -1: return "手动关闭";
            case -2: return "超时关闭";
            case -3: return "商家关闭";
            default: return "未知";
        }
    }

    /**
     * 获取支付方式文本
     */
    private String getPayTypeText(Integer payType) {
        if (payType == null) return "未知";

        switch (payType) {
            case 1: return "支付宝支付";
            case 2: return "微信支付";
            default: return "未知";
        }
    }

    /**
     * 获取开票状态文本
     */
    private String getBillStatusText(Integer isBill) {
        if (isBill == null) return "未知";

        switch (isBill) {
            case 1: return "未开票";
            case 2: return "开票申请中";
            case 3: return "商家同意开票";
            case 4: return "已开票";
            default: return "未知";
        }
    }

    /**
     * 获取退款状态文本
     */
    private String getRefundStatusText(String refundStatus) {
        if (refundStatus == null) return "-";

        switch (refundStatus) {
            case "用户申请退款": return "用户申请退款";
            case "业务员退款通过": return "业务员退款通过";
            case "退款成功": return "退款成功";
            case "退款失败": return "退款失败";
            default: return refundStatus;
        }
    }


    @GetMapping("/orders/{orderId}")
    @ApiOperation(value = "订单详情接口", notes = "传参为订单号")
    public Result<NewBeeMallOrderDetailVO> orderDetailPage(@ApiParam(value = "订单号") @PathVariable("orderId") Long orderId, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        return ResultGenerator.genSuccessResult(newBeeMallOrderService.getOrderDetailByOrderId(orderId));
    }

    /**
     * 配货
     */
    @RequestMapping(value = "/orders/checkDone", method = RequestMethod.PUT)
    @ApiOperation(value = "修改订单状态为配货成功", notes = "批量修改")
    @PreventDuplicateSubmit(key = "checkDone", expire = 3, message = "订单正在处理中，请勿重复提交")
    public Result checkDone(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (batchIdParam == null || batchIdParam.getIds().length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = newBeeMallOrderService.checkDone(batchIdParam.getIds());
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    /**
     * 出库
     */
    @RequestMapping(value = "/orders/checkOut", method = RequestMethod.PUT)
    @ApiOperation(value = "修改订单状态为已出库", notes = "批量修改")
    @PreventDuplicateSubmit(key = "checkOut", expire = 3, message = "订单正在处理中，请勿重复提交")
    public Result checkOut(@RequestBody BatchIdSendParam batchIdParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (batchIdParam == null || batchIdParam.getIds().length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = newBeeMallOrderService.checkOut(batchIdParam);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    /**
     * 关闭订单
     */
    @RequestMapping(value = "/orders/close", method = RequestMethod.PUT)
    @ApiOperation(value = "修改订单状态为商家关闭", notes = "批量修改")
    @PreventDuplicateSubmit(key = "order_close", expire = 3, message = "订单正在处理中，请勿重复提交")
    public Result closeOrder(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (batchIdParam == null || batchIdParam.getIds().length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = newBeeMallOrderService.closeOrder(batchIdParam.getIds());
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    @RequestMapping(value ="/orders/refundOrder", method = RequestMethod.PUT)
    @ApiOperation(value = "退款", notes = "退款")
    @Log(module = "退款", action = "退款")
    @PreventDuplicateSubmit(key = "refundOrder", expire = 3, message = "订单正在处理中，请勿重复提交")
    public Result refundOrder(@RequestBody RefundParam batchIdParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("退款adminUser:{}", adminUser.toString());
        String payResult = newBeeMallOrderService.refundOrder(batchIdParam.getOrderNo());
        if (ServiceResultEnum.SUCCESS.getResult().equals(payResult)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(payResult);
        }
    }


    @RequestMapping(value ="/orders/refundYwyOrder", method = RequestMethod.PUT)
    @ApiOperation(value = "业务员退款", notes = "业务员退款")
    @Log(module = "业务员退款", action = "业务员退款")
    @PreventDuplicateSubmit(key = "refundYwyOrder", expire = 3, message = "订单正在处理中，请勿重复提交")
    public Result refundYwyOrder(@RequestBody RefundParam batchIdParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("业务员退款adminUser:{}", adminUser.toString());
        String payResult = newBeeMallOrderService.refundYwyOrder(batchIdParam.getOrderNo());
        if (ServiceResultEnum.SUCCESS.getResult().equals(payResult)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(payResult);
        }
    }



    @RequestMapping(value ="/orders/approveInvoice", method = RequestMethod.PUT)
    @ApiOperation(value = "同意开票接口", notes = "同意开票接口")
    @Log(module = "同意开票接口", action = "同意开票接口")
    @PreventDuplicateSubmit(key = "approveInvoice", expire = 3, message = "订单正在处理中，请勿重复提交")
    public Result approveInvoice(@RequestBody InvoiceApplyParam invoiceApplyParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("同意开票接口adminUser:{}", adminUser.toString());
       return newBeeMallOrderService.approveInvoice(invoiceApplyParam);
    }


}
